import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

public class VideoPlayer extends Application {
    private List<VideoPlayerControl> videoPlayers = new ArrayList<>();
    private GridPane videoContainer;
    private static final int COLUMNS = 3;

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("多窗口视频播放器");

        // 创建主布局
        VBox root = new VBox();
        root.setStyle("-fx-background-color: #2b2b2b;");

        // 创建滚动区域
        ScrollPane scrollPane = new ScrollPane();
        scrollPane.setStyle("-fx-background: #2b2b2b; -fx-border-color: transparent;");
        scrollPane.setFitToWidth(true);

        // 创建视频容器
        videoContainer = new GridPane();
        videoContainer.setHgap(10);
        videoContainer.setVgap(10);
        videoContainer.setPadding(new Insets(10));
        videoContainer.setStyle("-fx-background-color: #2b2b2b;");

        scrollPane.setContent(videoContainer);
        VBox.setVgrow(scrollPane, Priority.ALWAYS);

        // 创建底部控制栏
        HBox bottomControls = createBottomControls();
        bottomControls.setStyle("-fx-background-color: #1e1e1e; -fx-border-color: #404040; -fx-border-width: 1 0 0 0;");

        root.getChildren().addAll(scrollPane, bottomControls);

        // 设置场景
        Scene scene = new Scene(root, 1200, 800);
        primaryStage.setScene(scene);
        primaryStage.show();

        // 加载默认文件夹
        loadDefaultFolder();
    }

    private HBox createBottomControls() {
        HBox controls = new HBox(10);
        controls.setAlignment(Pos.CENTER_LEFT);
        controls.setPadding(new Insets(10));

        Button selectFolderBtn = new Button("选择文件夹");
        Button playAllBtn = new Button("全部播放");
        Button stopAllBtn = new Button("全部停止");

        String buttonStyle = """
            -fx-background-color: #3a3a3a;
            -fx-text-fill: white;
            -fx-min-width: 100px;
            -fx-padding: 8 15;
            """;
        selectFolderBtn.setStyle(buttonStyle);
        playAllBtn.setStyle(buttonStyle);
        stopAllBtn.setStyle(buttonStyle);

        selectFolderBtn.setOnAction(e -> selectFolder());
        playAllBtn.setOnAction(e -> playAll());
        stopAllBtn.setOnAction(e -> stopAll());

        controls.getChildren().addAll(selectFolderBtn, playAllBtn, stopAllBtn);
        return controls;
    }

    private void selectFolder() {
        DirectoryChooser directoryChooser = new DirectoryChooser();
        directoryChooser.setTitle("选择视频文件夹");
        File folder = directoryChooser.showDialog(null);
        if (folder != null) {
            loadVideosFromFolder(folder);
        }
    }

    private void loadDefaultFolder() {
        File defaultFolder = new File("D:\\test\\video");
        if (defaultFolder.exists()) {
            loadVideosFromFolder(defaultFolder);
        }
    }

    private void loadVideosFromFolder(File folder) {
        // 清除现有视频
        videoPlayers.forEach(VideoPlayerControl::dispose);
        videoPlayers.clear();
        videoContainer.getChildren().clear();

        File[] files = folder.listFiles((dir, name) -> {
            String lowercaseName = name.toLowerCase();
            return lowercaseName.endsWith(".mp4") || lowercaseName.endsWith(".avi") ||
                   lowercaseName.endsWith(".mkv") || lowercaseName.endsWith(".mov");
        });

        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                int row = i / COLUMNS;
                int col = i % COLUMNS;
                try {
                    VideoPlayerControl videoPlayer = new VideoPlayerControl(files[i]);
                    videoPlayers.add(videoPlayer);
                    videoContainer.add(videoPlayer, col, row);
                } catch (Exception e) {
                    System.err.println("Error loading video: " + files[i].getName());
                    e.printStackTrace();
                }
            }
        }
    }

    private void playAll() {
        videoPlayers.forEach(VideoPlayerControl::play);
    }

    private void stopAll() {
        videoPlayers.forEach(VideoPlayerControl::stop);
    }

    public static void main(String[] args) {
        launch(args);
    }
}

class VideoPlayerControl extends VBox {
    private final MediaPlayer mediaPlayer;
    private final MediaView mediaView;
    private final Slider progressSlider;
    private final Label timeLabel;
    private final Button playButton;
    private final Slider volumeSlider;
    private final ToggleButton muteButton;
    private final AtomicBoolean isUserSeeking = new AtomicBoolean(false);

    public VideoPlayerControl(File file) {
        setStyle("-fx-background-color: #1e1e1e; -fx-padding: 5; -fx-spacing: 5;");
        setMaxWidth(Double.MAX_VALUE);

        // 创建媒体播放器
        Media media = new Media(file.toURI().toString());
        mediaPlayer = new MediaPlayer(media);
        mediaView = new MediaView(mediaPlayer);
        mediaView.setFitWidth(320);
        mediaView.setFitHeight(180);
        mediaView.setStyle("-fx-background-color: black;");

        // 文件名标签
        Label nameLabel = new Label(file.getName());
        nameLabel.setStyle("-fx-text-fill: white; -fx-font-size: 10px;");
        nameLabel.setAlignment(Pos.CENTER);
        nameLabel.setMaxWidth(Double.MAX_VALUE);

        // 进度条和时间标签
        HBox progressBox = new HBox(5);
        progressBox.setAlignment(Pos.CENTER);
        timeLabel = new Label("00:00 / 00:00");
        timeLabel.setStyle("-fx-text-fill: white; -fx-font-size: 10px;");
        progressSlider = new Slider();
        progressSlider.setMaxWidth(Double.MAX_VALUE);
        HBox.setHgrow(progressSlider, Priority.ALWAYS);
        progressBox.getChildren().addAll(timeLabel, progressSlider);

        // 控制按钮
        HBox controlBox = new HBox(15);
        controlBox.setAlignment(Pos.CENTER);

        // 播放控制
        HBox playbackControls = new HBox(5);
        Button rewindButton = new Button("⏪");
        playButton = new Button("▶");
        Button forwardButton = new Button("⏩");
        Button fullscreenButton = new Button("⛶");

        String buttonStyle = """
            -fx-background-color: #3a3a3a;
            -fx-text-fill: white;
            -fx-min-width: 24px;
            -fx-min-height: 24px;
            -fx-padding: 2;
            """;
        rewindButton.setStyle(buttonStyle);
        playButton.setStyle(buttonStyle);
        forwardButton.setStyle(buttonStyle);
        fullscreenButton.setStyle(buttonStyle);

        playbackControls.getChildren().addAll(rewindButton, playButton, forwardButton, fullscreenButton);

        // 音量控制
        HBox volumeControls = new HBox(5);
        muteButton = new ToggleButton("🔊");
        muteButton.setStyle(buttonStyle);
        volumeSlider = new Slider(0, 100, 100);
        volumeSlider.setPrefWidth(60);
        volumeControls.getChildren().addAll(muteButton, volumeSlider);

        controlBox.getChildren().addAll(playbackControls, volumeControls);

        // 添加所有组件
        getChildren().addAll(nameLabel, mediaView, progressBox, controlBox);

        // 设置事件处理
        setupEventHandlers();

        // 自动开始播放并跳转到三分之一处
        mediaPlayer.setOnReady(() -> {
            Duration duration = mediaPlayer.getMedia().getDuration();
            mediaPlayer.seek(duration.divide(3));
            mediaPlayer.play();
        });
    }

    private void setupEventHandlers() {
        // 播放/暂停
        playButton.setOnAction(e -> {
            if (mediaPlayer.getStatus() == MediaPlayer.Status.PLAYING) {
                mediaPlayer.pause();
                playButton.setText("▶");
            } else {
                mediaPlayer.play();
                playButton.setText("⏸");
            }
        });

        // 进度条
        progressSlider.setOnMousePressed(e -> isUserSeeking.set(true));
        progressSlider.setOnMouseReleased(e -> {
            isUserSeeking.set(false);
            mediaPlayer.seek(Duration.seconds(progressSlider.getValue()));
        });

        // 音量控制
        muteButton.setOnAction(e -> {
            mediaPlayer.setMute(muteButton.isSelected());
            muteButton.setText(muteButton.isSelected() ? "🔈" : "🔊");
        });

        volumeSlider.valueProperty().addListener((obs, oldVal, newVal) -> {
            mediaPlayer.setVolume(newVal.doubleValue() / 100.0);
            if (newVal.doubleValue() > 0) {
                muteButton.setSelected(false);
                muteButton.setText("🔊");
            }
        });

        // 更新进度
        mediaPlayer.currentTimeProperty().addListener((obs, oldTime, newTime) -> {
            if (!isUserSeeking.get()) {
                Platform.runLater(() -> {
                    Duration current = mediaPlayer.getCurrentTime();
                    Duration total = mediaPlayer.getTotalDuration();
                    progressSlider.setValue(current.toSeconds());
                    timeLabel.setText(String.format("%02d:%02d / %02d:%02d",
                            (int) current.toMinutes(),
                            (int) current.toSeconds() % 60,
                            (int) total.toMinutes(),
                            (int) total.toSeconds() % 60));
                });
            }
        });
    }

    public void play() {
        mediaPlayer.play();
        playButton.setText("⏸");
    }

    public void stop() {
        mediaPlayer.stop();
        playButton.setText("▶");
    }

    public void dispose() {
        mediaPlayer.dispose();
    }
} 